import React, { useState } from 'react';
import { useColorStore, useRecommendationStore } from '@/stores';
import { Button } from '@/components/ui/Button';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
import { ColorUtils } from '@/utils/color';
import { ColorSchemeType } from '@/types';

type MoodType = 'energetic' | 'calm' | 'warm' | 'cool' | 'professional' | 'playful';

export const RecommendationsPage: React.FC = () => {
  const { currentColor, addSelectedColor } = useColorStore();
  const {
    recommendations,
    personalizedRecommendations,
    trendingRecommendations,
    seasonalRecommendations,
    isLoading,
    generateRecommendations,
    generatePersonalizedRecommendations,
    generateTrendingRecommendations,
    generateSeasonalRecommendations,
    generateMoodBasedRecommendations
  } = useRecommendationStore();

  const [activeTab, setActiveTab] = useState<'theory' | 'personal' | 'trending' | 'seasonal' | 'mood'>('theory');
  const [selectedSchemeType, setSelectedSchemeType] = useState<ColorSchemeType>('complementary');
  const [selectedMood, setSelectedMood] = useState<MoodType>('calm');

  const tabs = [
    { id: 'theory', name: '色彩理论', icon: '🎨' },
    { id: 'personal', name: '个性化', icon: '👤' },
    { id: 'trending', name: '流行趋势', icon: '🔥' },
    { id: 'seasonal', name: '季节色彩', icon: '🍂' },
    { id: 'mood', name: '情绪配色', icon: '💭' }
  ];

  const schemeTypes = [
    { id: 'complementary', name: '互补色', description: '色环上相对的颜色，形成强烈对比' },
    { id: 'analogous', name: '类似色', description: '色环上相邻的颜色，和谐统一' },
    { id: 'triadic', name: '三角色', description: '色环上等距的三种颜色，平衡而鲜明' },
    { id: 'tetradic', name: '四角色', description: '色环上等距的四种颜色，丰富多彩' },
    { id: 'monochromatic', name: '单色调', description: '同一色相的不同明度和饱和度' }
  ];

  const moods = [
    { id: 'energetic', name: '活力', description: '充满活力和激情的配色' },
    { id: 'calm', name: '平静', description: '宁静舒缓的配色' },
    { id: 'warm', name: '温暖', description: '温馨亲切的暖色调' },
    { id: 'cool', name: '清凉', description: '清新冷静的冷色调' },
    { id: 'professional', name: '专业', description: '商务专业的配色方案' },
    { id: 'playful', name: '活泼', description: '有趣生动的配色' }
  ];

  const handleGenerateRecommendations = async () => {
    switch (activeTab) {
      case 'theory':
        await generateRecommendations(currentColor, selectedSchemeType);
        break;
      case 'personal':
        await generatePersonalizedRecommendations(currentColor);
        break;
      case 'trending':
        await generateTrendingRecommendations(currentColor);
        break;
      case 'seasonal':
        await generateSeasonalRecommendations(currentColor);
        break;
      case 'mood':
        await generateMoodBasedRecommendations(currentColor, selectedMood);
        break;
    }
  };

  const getActiveRecommendations = () => {
    switch (activeTab) {
      case 'personal':
        return personalizedRecommendations;
      case 'trending':
        return trendingRecommendations;
      case 'seasonal':
        return seasonalRecommendations;
      default:
        return recommendations;
    }
  };

  const handleAddColor = (color: any) => {
    addSelectedColor(color);
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">智能推荐</h1>
        <p className="text-gray-600">基于不同算法和偏好生成色彩搭配建议</p>
      </div>

      {/* 当前颜色 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">基础颜色</h2>
        <div className="flex items-center space-x-4">
          <div
            className="w-16 h-16 rounded-lg border border-gray-300"
            style={{ backgroundColor: currentColor.hex }}
          />
          <div>
            <p className="font-mono text-lg">{currentColor.hex}</p>
            <p className="text-gray-600">
              RGB({currentColor.rgb.r}, {currentColor.rgb.g}, {currentColor.rgb.b})
            </p>
            <p className="text-gray-600">
              HSL({currentColor.hsl.h}°, {currentColor.hsl.s}%, {currentColor.hsl.l}%)
            </p>
          </div>
          <div className="flex-1" />
          <Button onClick={() => window.location.href = '/color-picker'}>
            更换颜色
          </Button>
        </div>
      </div>

      {/* 推荐类型选择 */}
      <div className="bg-white rounded-lg shadow-md">
        <div className="border-b border-gray-200">
          <nav className="-mb-px flex space-x-8 px-6">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`
                  py-4 px-1 border-b-2 font-medium text-sm whitespace-nowrap
                  ${activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }
                `}
              >
                <span className="mr-2">{tab.icon}</span>
                {tab.name}
              </button>
            ))}
          </nav>
        </div>

        <div className="p-6">
          {/* 色彩理论选项 */}
          {activeTab === 'theory' && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">选择配色方案</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {schemeTypes.map((scheme) => (
                  <div
                    key={scheme.id}
                    className={`
                      p-4 border rounded-lg cursor-pointer transition-colors
                      ${selectedSchemeType === scheme.id
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-gray-300'
                      }
                    `}
                    onClick={() => setSelectedSchemeType(scheme.id as ColorSchemeType)}
                  >
                    <h4 className="font-medium text-gray-900">{scheme.name}</h4>
                    <p className="text-sm text-gray-600 mt-1">{scheme.description}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 情绪配色选项 */}
          {activeTab === 'mood' && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">选择情绪风格</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {moods.map((mood) => (
                  <div
                    key={mood.id}
                    className={`
                      p-4 border rounded-lg cursor-pointer transition-colors
                      ${selectedMood === mood.id
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-gray-300'
                      }
                    `}
                    onClick={() => setSelectedMood(mood.id as MoodType)}
                  >
                    <h4 className="font-medium text-gray-900">{mood.name}</h4>
                    <p className="text-sm text-gray-600 mt-1">{mood.description}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 其他类型的说明 */}
          {activeTab === 'personal' && (
            <div className="bg-blue-50 rounded-lg p-4">
              <h3 className="text-lg font-medium text-blue-900">个性化推荐</h3>
              <p className="text-blue-700 mt-1">
                基于你的历史使用习惯和偏好生成个性化的色彩搭配建议
              </p>
            </div>
          )}

          {activeTab === 'trending' && (
            <div className="bg-orange-50 rounded-lg p-4">
              <h3 className="text-lg font-medium text-orange-900">流行趋势</h3>
              <p className="text-orange-700 mt-1">
                基于当前设计趋势和流行色彩生成时尚的搭配方案
              </p>
            </div>
          )}

          {activeTab === 'seasonal' && (
            <div className="bg-green-50 rounded-lg p-4">
              <h3 className="text-lg font-medium text-green-900">季节色彩</h3>
              <p className="text-green-700 mt-1">
                根据当前季节特色生成适合季节氛围的色彩搭配
              </p>
            </div>
          )}

          {/* 生成按钮 */}
          <div className="mt-6">
            <Button
              onClick={handleGenerateRecommendations}
              disabled={isLoading}
              className="w-full md:w-auto"
            >
              {isLoading ? (
                <>
                  <LoadingSpinner size="small" className="mr-2" />
                  生成中...
                </>
              ) : (
                '生成推荐'
              )}
            </Button>
          </div>
        </div>
      </div>

      {/* 推荐结果 */}
      {getActiveRecommendations().length > 0 && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">推荐结果</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
            {getActiveRecommendations().map((color, index) => (
              <div
                key={index}
                className="group relative"
              >
                <div
                  className="w-full aspect-square rounded-lg border border-gray-300 cursor-pointer transition-transform hover:scale-105"
                  style={{ backgroundColor: color.hex }}
                  onClick={() => handleAddColor(color)}
                  title={`点击添加 ${color.hex}`}
                />
                <div className="mt-2 text-center">
                  <p className="text-sm font-mono text-gray-700">{color.hex}</p>
                  <p className="text-xs text-gray-500">
                    {ColorUtils.isLight(color) ? '浅色' : '深色'}
                  </p>
                </div>
                <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <Button
                    size="sm"
                    onClick={() => handleAddColor(color)}
                    className="w-6 h-6 p-0 rounded-full"
                  >
                    +
                  </Button>
                </div>
              </div>
            ))}
          </div>

          {/* 批量操作 */}
          <div className="mt-6 flex space-x-2">
            <Button
              variant="outline"
              onClick={() => {
                getActiveRecommendations().forEach(color => handleAddColor(color));
              }}
            >
              全部添加到调色板
            </Button>
            <Button
              variant="outline"
              onClick={handleGenerateRecommendations}
              disabled={isLoading}
            >
              重新生成
            </Button>
          </div>
        </div>
      )}

      {/* 使用提示 */}
      <div className="bg-gray-50 rounded-lg p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-2">使用提示</h3>
        <ul className="text-sm text-gray-600 space-y-1">
          <li>• 点击推荐的颜色可以直接添加到你的调色板</li>
          <li>• 尝试不同的推荐类型，发现更多搭配可能性</li>
          <li>• 个性化推荐会根据你的使用历史不断优化</li>
          <li>• 保存喜欢的搭配方案，建立你的色彩库</li>
        </ul>
      </div>
    </div>
  );
};